package leetcode.code0719;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int smallestDistancePair(int[] nums, int k) {
		Arrays.sort(nums);
		int l = 0, r = 1000000;
		int ans = 0;
		while (l <= r) {
			int size = l + ((r - l) >> 1);
			int num = this.find(nums, size);
			if (num >= k) {
				ans = size;
				r = size - 1;
			} else {
				l = size + 1;
			}
		}
		return ans;
	}

	private int find(int[] nums, int size) {
		int len = nums.length;
		int l = 0, r = 0;
		int ans = 0;
		while (l < len) {
			while (r < len && nums[r] - nums[l] <= size) {
				r++;
			}
			ans += r - l - 1;
			l++;
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(58, this.smallestDistancePair(H.str2array3("[62,100,4]"), 2));
		H.compare(36, this.smallestDistancePair(H.str2array3("[38,33,57,65,13,2,86,75,4,56]"), 26));
		H.compare(0, this.smallestDistancePair(H.str2array3("[1,3,1]"), 1));
		H.compare(0, this.smallestDistancePair(H.str2array3("[1,1,1]"), 2));
		H.compare(5, this.smallestDistancePair(H.str2array3("[1,6,1]"), 3));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
